package com.ysu.his.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ysu.his.admin.mapper.RegisterLevelMapper;
import com.ysu.his.admin.service.RegisterLevelService;
import com.ysu.his.dto.RegisterLevelDto;
import com.ysu.his.entity.registration.RegistrationLevel;
import com.ysu.his.exception.HISException;
import com.ysu.his.vo.RegisterLevelVo;
import com.ysu.his.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RegisterLevelServiceImpl implements RegisterLevelService
{

    @Autowired
    private RegisterLevelMapper registerLevelMapper;


    @Override
    public PageInfo<RegisterLevelVo> getRegisterLevelByPage(Integer page, Integer limit, RegisterLevelDto registerLevelDto)
    {
        PageHelper.startPage(page, limit);

        List<RegisterLevelVo> registerLevelVoList = registerLevelMapper.getRegisterLevelByPage(registerLevelDto);
        PageInfo<RegisterLevelVo> pageInfo = new PageInfo<>(registerLevelVoList);

        return pageInfo;
    }

    @Override
    public void addRegisterLevel(RegistrationLevel registrationLevel)
    {
        canAddOrUpdate(registrationLevel);

        registerLevelMapper.addRegisterLevel(registrationLevel);
    }

    @Override
    public void updateRegisterLevel(RegistrationLevel registrationLevel)
    {
        canAddOrUpdate(registrationLevel);

        registerLevelMapper.updateRegisterLevel(registrationLevel);
    }

    private Boolean canAddOrUpdate(RegistrationLevel registrationLevel)
    {
        List<Long> doctorId = registerLevelMapper.doctorIsAvailable(registrationLevel.getDoctorId());
        if (registrationLevel.getId() == null && !CollectionUtils.isEmpty(doctorId))
        {
            throw new HISException(ResultCodeEnum.DOCTOR_REGISTERED);
        }
        if (!CollectionUtils.isEmpty(doctorId))
        {
            List<Long> collect = doctorId.stream().filter(id -> id == registrationLevel.getDoctorId())
                    .collect(Collectors.toList());
            if (collect.size()!=doctorId.size())
            {
                throw new HISException(ResultCodeEnum.DOCTOR_REGISTERED);
            }
        }

        return true;
    }
}
